﻿using System.Collections.Generic;

namespace net.entity.framework.common {
    public static class DictionaryExtender {
        public delegate TValue CreateDelegate<TKey, TValue>(TKey key);

        public static bool LookupContains<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key) {
            return dict.ContainsKey(key);
        }

        public static TValue Lookup<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, bool strict) {
            if (dict.ContainsKey(key)) {
                return dict[key];
            }
            if (strict) {
                throw new KeyNotFoundException();
            }
            return default(TValue);
        }

        public static TValue LookupOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key,
                                                           TValue defaultValue) {
            return dict.ContainsKey(key) ? dict[key] : defaultValue;
        }

        public static TValue LookupOrCreate<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key,
                                                          CreateDelegate<TKey, TValue> createDelegate) {
            if (dict.ContainsKey(key)) {
                return dict[key];
            }
            var value = createDelegate.Invoke(key);
            dict.Add(key, value);
            return dict[key];
        }
    }
}